package es.mfp.practicos.view.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter(value = "dateConverter")
public class DateConverter implements Converter {

	private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {

		Date res = null;
		
		if(arg2 == null || arg2.trim().equals("") || arg2.equals("...")){
			return null;
		}

		try {
			res = dateFormat.parse(arg2);
		} catch (ParseException e) {
			throw new IllegalArgumentException("Objeto no convertible a fecha: " + arg2);
		}

		return res;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		if(arg2 == null){
			return null;
		}
		Date d = (Date) arg2;
		return dateFormat.format(d);
	}

}
